package net.pimpas.visitor;

import java.util.ArrayList;
import java.util.List;

import net.pimpas.context.DefaultFrameworkContext;
import net.pimpas.core.context.FrameworkContext;
import net.pimpas.core.visitor.BaseClassVisitor;
import net.pimpas.core.visitor.BaseDirectoryVisitor;
import net.pimpas.core.visitor.BaseFileVisitor;
import net.pimpas.core.visitor.ClassPathVisitor;
import net.pimpas.core.visitor.ClassPathVisitorDefault;
import net.pimpas.core.visitor.Visitor;
import net.pimpas.framework.PimpasFramework;
import net.pimpas.util.reflection.ReflectionUtil;

import org.apache.log4j.Logger;

public final class BaseVisitorClass extends BaseClassVisitor {
	private static Logger logger = Logger.getLogger(BaseVisitorClass.class);
	private static List<Class<?>> visitors = new ArrayList<Class<?>>();

	@Override
	public void visitClass(Class<?> clazz) {
		if(ReflectionUtil.isSubclass(clazz, Visitor.class) && clazz != this.getClass() &&
				clazz != BaseClassVisitor.class && clazz != BaseDirectoryVisitor.class &&
				clazz != BaseFileVisitor.class && clazz != ClassPathVisitor.class &&
				clazz != ClassPathVisitorDefault.class && clazz != Visitor.class) {
			logger.debug("[ADDING VISITOR: "+clazz.getName()+"]");
			visitors.add(clazz);
		}
		// get framework context
		if(ReflectionUtil.isSubclass(clazz, FrameworkContext.class) &&
				!clazz.isInterface() && clazz != DefaultFrameworkContext.class) {
			logger.debug("[SETTING FRAMEWORK CONTEXT: "+clazz+"]");
			try {
				PimpasFramework.getCurrentInstance().setContext((FrameworkContext) clazz.newInstance());
			} catch (InstantiationException e) {
				logger.error("[ERROR]: Error setting frameworkContext", e);
			} catch (IllegalAccessException e) {
				logger.error("[ERROR]: Error setting frameworkContext", e);
			}
		}
	}
	
	public static List<Class<?>> getVisitorClasses( ) {
		return visitors;
	}
}